package com.mspbots.cw.trigger;


import com.mspbots.api.client.CoreClient;
import com.mspbots.cw.amqp.model.TenantSchedule;
import com.mspbots.cw.amqp.model.TriggerEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.data.r2dbc.core.DatabaseClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

import static com.mspbots.common.TriggerEvent.CW_TICKET_SCHEDULE_SCHEDULE;


/**
 * com.mspbots.cw.trigger.TicketScheduleEvent
 *
 * @author Jason
 * @date 2019/12/13
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ScheduleScheduleEvent {

    private final  CoreClient coreClient;
    private final  DatabaseClient databaseClient;
    private final  RabbitMessagingTemplate messagingTemplate;

    @Scheduled(fixedDelayString ="${mspbots.fixedDelay.schedule}")
    public void produce() {
        Long time  = System.currentTimeMillis();
        log.debug("ScheduleScheduleEvent...current time..{}",time);
        this.databaseClient.execute("select id from tenant where status_id = 1")
                .as(Long.class)
                .fetch()
                .all()
                .filter(tenantId -> tenantId > 0)
                .flatMap(tenantId -> {
                    log.debug("ScheduleScheduleEvent::flatMap:tenantId:{}",tenantId);
                    log.debug("ScheduleScheduleEvent::flatMap:LocalDateTime.now():{}",LocalDateTime.now());
                    return this.databaseClient.execute("select * from tenant_schedule where done_flag = false and tenant_id = :tenantId " +
                            "and date_start > now() and  date_start <= now()  + (2 || ' hour')::interval and identifier is not null ")
                            .as(TenantSchedule.class)
                            .bind("tenantId",tenantId)
                            .fetch()
                            .all();
//                            .filter(ts -> !ObjectUtils.isEmpty(ts.getDateStart()) && ts.getDateStart().isAfter(LocalDateTime.now())
//                                    && ts.getDateStart().isBefore(LocalDateTime.now().plusHours(2)));
                    }
                )
                .switchIfEmpty(t -> log.error("ScheduleScheduleEvent::switchIfEmpty:"+t))
                .flatMap(tenantSchedule ->{
                    Map<String, Object> userMappingParam = Map.of(
                            "tenantId", tenantSchedule.getTenantId(),
                            "identifier", tenantSchedule.getIdentifier());
                    return this.coreClient.get("/user-mapping/detail", userMappingParam)
                            .map( u -> {
                                TriggerEvent triggerEvent = new TriggerEvent();
                                log.debug("ScheduleScheduleEvent::u :{}",u);
                                triggerEvent.setTenantId(Long.valueOf(tenantSchedule.getTenantId()));
                                triggerEvent.setEventName(CW_TICKET_SCHEDULE_SCHEDULE.getEvent());
                                triggerEvent.setScope(CW_TICKET_SCHEDULE_SCHEDULE.getScope());
                                triggerEvent.setPayload(tenantSchedule.getExtend());
                                triggerEvent.setUserInfo(u);
                                return triggerEvent;
                            });

                })
                .subscribe(triggerEvent -> {
                        log.debug("triggerEvent::start::{}",triggerEvent);
                        this.messagingTemplate.convertAndSend("msp.trigger.event", "", triggerEvent);
                        log.debug("ScheduleScheduleEvent::end:tenantId:{},userId:{},objectId:{}",triggerEvent.getTenantId(),triggerEvent.getUserInfo().get("tenantUserId").asText(),triggerEvent.getPayload().get("objectId").asText());
                    }, error -> {
                            log.error("ScheduleScheduleEvent::error::{}",error);

                  });


    }

}
